package top.easyblog.core.support.filter;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import top.easyblog.core.util.NetWorkUtils;

import javax.servlet.http.HttpServletRequest;

import static top.easyblog.core.support.filter.TransformContext.PARAM_HTTP_SERVLET_REQUEST;

/**
 * 提取请求头过滤器
 */
@Component
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ExtractRequestHeaderTransformFilter implements TransformFilter {

    private static final String UA_KEY = "User-Agent";
    private static final String COOKIE_KEY = "Cookie";

    @Override
    public void init(TransformContext context) {

    }

    @Override
    public void doFilter(TransformFilterChain chain, TransformContext context) {
        try {
            context.setParam(TransformContext.PARAM_UA_KEY, context.getHeader("user-agent"));
            HttpServletRequest request = context.getParam(PARAM_HTTP_SERVLET_REQUEST);
            context.setParam(TransformContext.PARAM_CLIENT_IP_KEY, NetWorkUtils.getRequestSourceIp(request));
            context.setParam(TransformContext.PARAM_REFERER_KEY, context.getHeader("referer"));
            context.setParam(TransformContext.PARAM_REMOTE_HOST_NAME_KEY, context.getHeader("host"));
        } finally {
            context.releaseHeaders();
        }
        chain.doFilter(context);
    }

    @Override
    public int order() {
        return 1;
    }

}
